<template>
  <div class="dictionary-assist">
    <je-modal
      v-model:visible="visibleModule"
      :title="`${modalType == 'assistDept' ? '部门辅助' : '字典辅助'}`"
      width="600px"
      class="dictionary-model"
      height="auto"
      :resize="false"
      :maximizable="false"
      @close="cancelModal"
    >
      <template #buttons="modal">
        <je-button
          key="save"
          type="primary"
          :disabled="btnDisabled"
          :loading="btnLoading"
          @click="addModule(modal)"
        >
          确定
        </je-button>
        <je-button key="back" @click="cancelModal">取消</je-button>
      </template>
      <div class="top-explain">
        <p class="explain-one">通过选择数据字典快速的为表添加字段</p>
        <p class="explain-two">【CODE项编码、NAME项名称、ID项主键】按需选择</p>
      </div>
      <div class="dictionary-form">
        <je-form
          ref="formRefModule"
          layout="horizontal"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :model="modelRef"
        >
          <je-form-item label="字典" v-bind="validateInfos.ddName" name="ddName">
            <je-grid-select
              v-model:value="modelRef.ddName"
              :select-options="{ title: '选择字典' }"
              name="ddName"
              editable
              :disabled="modalType == 'assistDept'"
              config-info="JE_CORE_DICTIONARY,ddName~ddCode~ddType,DICTIONARY_DDNAME~DICTIONARY_DDCODE~DICTIONARY_DDTYPE,S"
              :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
              @change="gridSelctChange"
              @select="selectFunc"
            />
          </je-form-item>
          <je-form-item label="名称" style="margin-bottom: 0px">
            <je-row type="flex" justify="space-between" align="middle">
              <je-col :span="8">
                <je-form-item>
                  <je-input v-model:value="modelRef.name_je" :disabled="disable" />
                </je-form-item>
              </je-col>
              <je-col :span="8">
                <je-form-item v-bind="validateInfos.name_dd">
                  <je-input v-model:value="modelRef.name_dd" @change="changeVerify" />
                </je-form-item>
              </je-col>
              <je-col :span="5">
                <je-form-item>
                  <je-input v-model:value="modelRef.name_info" :disabled="disable" />
                </je-form-item>
              </je-col>
              <je-col :span="1">
                <je-form-item>
                  <je-checkbox
                    v-model:checked="modelRef.nameChecked"
                    @change="loadColumnCode"
                  ></je-checkbox>
                </je-form-item>
              </je-col>
            </je-row>
          </je-form-item>
          <je-form-item label="编码">
            <je-row type="flex" justify="space-between" align="middle">
              <je-col :span="8"
                ><je-input v-model:value="modelRef.code_je" :disabled="disable"
              /></je-col>
              <je-col :span="8"
                ><je-input v-model:value="modelRef.code_dd" :disabled="disable"
              /></je-col>
              <je-col :span="5"
                ><je-input v-model:value="modelRef.code_info" :disabled="disable"
              /></je-col>
              <je-col :span="1"
                ><je-checkbox
                  v-model:checked="modelRef.codeChecked"
                  @change="loadColumnCode"
                ></je-checkbox
              ></je-col>
            </je-row>
          </je-form-item>
          <je-form-item label="主键">
            <je-row type="flex" justify="space-between" align="middle">
              <je-col :span="8"
                ><je-input v-model:value="modelRef.id_je" :disabled="disable"
              /></je-col>
              <je-col :span="8"
                ><je-input v-model:value="modelRef.id_dd" :disabled="disable"
              /></je-col>
              <je-col :span="5"
                ><je-input v-model:value="modelRef.id_info" :disabled="disable"
              /></je-col>
              <je-col :span="1"
                ><je-checkbox
                  v-model:checked="modelRef.idChecked"
                  @change="loadColumnCode"
                ></je-checkbox
              ></je-col>
            </je-row>
          </je-form-item>
        </je-form>
      </div>
    </je-modal>
  </div>
</template>
<script>
  import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue';
  import { Row, Col } from 'ant-design-vue';
  import { Input, Modal, Checkbox, Button, Form, InputSelect } from '@jecloud/ui';
  import { viewColumnCode, addColumnByDD } from '../../api/index';
  import { verifyData } from '../../helper/common';
  import { debounce, isEmpty } from '@jecloud/utils';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'DictionaryAssist',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeRow: Row,
      JeCol: Col,
      JeCheckbox: Checkbox,
      JeButton: Button,
      JeGridSelect: InputSelect.Grid,
    },
    props: {
      modalShow: {
        type: String,
        default: '',
      },
      tableData: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['changeData'],
    setup(props, { emit }) {
      //保存模块数据，关闭弹窗
      const visibleModule = ref(true);
      const btnDisabled = ref(false);
      const btnLoading = ref(false);
      const modalType = ref(props.modalShow);
      const data = reactive(props.tableData);
      const array = data.RESOURCETABLE_TABLECODE.split('_');
      const TableCode = array[array.length - 1] + '_';
      const modelRef = reactive({
        ddName: '',
        ddCode: '',
        ddType: '',
        name_je: TableCode,
        name_dd: '',
        name_info: '_NAME',
        nameChecked: true,
        code_je: TableCode,
        code_dd: '',
        code_info: '_CODE',
        codeChecked: true,
        id_je: TableCode,
        id_dd: '',
        id_info: '_ID',
        idChecked: false,
      });
      //如果是部门辅助
      if (modalType.value == 'assistDept') {
        modelRef.ddName = '部门查询树';
        modelRef.ddCode = 'JE_RBAC_DEPTTREE';
        modelRef.ddType = 'CUSTOM';
        modelRef.name_dd = 'DEPARTMENT';
        modelRef.code_dd = 'DEPARTMENT';
        modelRef.id_dd = 'DEPARTMENT';
      }

      onMounted(() => {
        nextTick(() => {
          loadColumnCode();
        });
      });

      //字段判重
      const loadColumnCode = () => {
        let codes = '';
        if (modelRef.nameChecked) {
          codes += TableCode + modelRef.name_dd + '_NAME,';
        }
        if (modelRef.codeChecked) {
          codes += TableCode + modelRef.code_dd + '_CODE,';
        }
        if (modelRef.idChecked) {
          codes += TableCode + modelRef.id_dd + '_ID,';
        }
        if (codes == '' || modelRef.name_dd == '') {
          btnDisabled.value = true;
          return;
        }
        viewColumnCode({
          JE_CORE_RESOURCETABLE_ID: data.JE_CORE_RESOURCETABLE_ID,
          addColumnCodes: codes,
        })
          .then((data) => {
            btnDisabled.value = false;
          })
          .catch((e) => {
            btnDisabled.value = true;
            // Modal.alert(e.message, 'error');
          });
      };

      const cancelModal = () => {
        visibleModule.value = false;
        emit('changeData');
      };
      const rulesRef = reactive({
        ddName: [verifyData.required],
        name_dd: [
          {
            max: 40,
            message: '不能大于40个字符',
          },
          {
            pattern: '^[A-Z_0-9]{0,100}$',
            message: '编码由大写字母、下划线、数字组成',
          },
          {
            required: true,
            message: '该输入项为必填项',
          },
        ],
      });
      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });
      const addModule = (modal) => {
        btnLoading.value = true;
        //保存数据逻辑
        addConnector(modal);
        return false;
      };

      const addConnector = (modal) => {
        validate()
          .then(() => {
            const addCodes = [];
            if (modelRef.nameChecked) {
              addCodes.push(modelRef.name_je + modelRef.name_dd + modelRef.name_info);
            }
            if (modelRef.codeChecked) {
              addCodes.push(modelRef.code_je + modelRef.code_dd + modelRef.code_info);
            }
            if (modelRef.idChecked) {
              addCodes.push(modelRef.id_je + modelRef.id_dd + modelRef.id_info);
            }
            if (addCodes.length > 0) {
              addColumnByDD({
                tableCode: 'JE_CORE_TABLECOLUMN',
                JE_CORE_RESOURCETABLE_ID: data.JE_CORE_RESOURCETABLE_ID,
                addColumnCodes: addCodes.join(','),
                ddCode: modelRef.ddCode,
                ddName: modelRef.ddName,
              })
                .then((data) => {
                  btnLoading.value = false;
                  modal.close();
                  emit('changeData', 'add');
                  Modal.notice(data.message, 'success');
                })
                .catch((e) => {
                  btnLoading.value = false;
                  Modal.alert(e.message, 'error');
                });
            } else {
              btnLoading.value = false;
            }
          })
          .catch((error) => {
            btnLoading.value = false;
          });
      };

      //值改变方法
      const changeVerify = debounce((searchValue) => {
        modelRef.code_dd = modelRef.name_dd;
        modelRef.id_dd = modelRef.name_dd;
        loadColumnCode();
      }, 300);

      //
      const selectFunc = ({ rows }) => {
        if (rows && rows.length > 0) {
          const codeArray = rows[0].DICTIONARY_DDCODE.split('_');
          const ddName = codeArray[codeArray.length - 1];
          modelRef.name_dd = ddName;
          modelRef.code_dd = ddName;
          modelRef.id_dd = ddName;
          loadColumnCode();
        }
      };

      //查询选择值改变事件
      const gridSelctChange = () => {
        if (isEmpty(modelRef.ddName)) {
          modelRef.name_dd = '';
          modelRef.code_dd = '';
          modelRef.id_dd = '';
        }
      };

      return {
        validateInfos,
        resetFields,
        modelRef,
        cancelModal,
        addModule,
        visibleModule,
        modalType,
        labelCol: { span: 3 },
        wrapperCol: { span: 20 },
        data,
        centered: true,
        loadColumnCode,
        disable: true,
        btnDisabled,
        btnLoading,
        changeVerify,
        selectFunc,
        gridSelctChange,
      };
    },
  });
</script>
<style lang="less" scoped>
  .dictionary-model {
    .top-explain {
      margin-bottom: 24px;
      position: relative;
      .explain-one {
        font-size: 14px;
        line-height: 22px;
        color: #606060;
        font-weight: Normal;
      }
      .explain-two {
        font-size: 14px;
        font-weight: Normal;
        color: #0000ff;
        line-height: 0px;
        position: absolute;
        left: -7px;
      }
    }
    .dictionary-form {
      background: #f9f9f9;
      padding: 25px 0 1px 0;
    }
  }
</style>
